<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div
      class="wrap-apply"
      :style="{top: GLOBAL.currentEnvironment ? '0' : '',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '0.76rem' : ''}"
    >
      <qrcode
        :qrcode="formData.qrcode"
        v-show="formData.qrcode"
        :camera="camera"
        :torchActive="torchActive"
        @switchCamera="switchCamera"
        @ClickFlash="ClickFlash"
        @turnCameraOff="turnCameraOff"
        @onDecode="onDecode"
        @onInit="onInit"
      />
      <div
        class="form-box"
        :style="{
          height: GLOBAL.currentEnvironment
            ? 'calc(100vh)'
            : 'calc(100vh - 1rem)',
        }"
      >
        <div
          class="top-info ordercode"
          style="background: #fff; padding: 0.16rem"
        >
          <div class="sel">
            <van-icon name="search" size="20" color="#999" />
            <input
              ref="PDAScan"
              v-model="batchCode"
              placeholder="请输入批次编号"
              @focus="focused = true"
              @input="inputscan"
              @blur="blurSearch"
            />
          </div>
          <span
            v-if="focused"
            @click="goSearch"
            style="margin: 2px 0 0 0.05rem; font-size: 0.14rem; color: #1890ff"
            >确定</span
          >
          <van-icon
            v-else
            @click="clickCode"
            size="30"
            color="#999"
            name="scan"
            style="margin: 2px 0 0 0.05rem"
          />
        </div>
        <div class="list-box">
          <div v-for="(g, i) in handleList" :key="i" class="item-height">
            <van-cell-group style="margin-top: 0.1rem">
              <div class="top-info ordercode" style="font-weight: 700">
                {{ `报工批次(${i + 1})`
                }}<van-icon
                  name="delete"
                  color="#1890ff"
                  size="20"
                  @click="clearItem(i)"
                />
              </div>
              <div style="height: 0.1rem"></div>
              <div class="bottomLine"></div>
            </van-cell-group>
            <van-cell-group v-show="!fakeData">
              <div class="top-info ordercode">{{ g.orderCode || "--" }}</div>
              <div class="top-info" style="font-weight: 600">
                {{ g.goodsCode || "--" }} | {{ g.goodsName || "--" }} |
                {{ g.goodsSpec || "--" }}
              </div>
              <div class="top-info" style="color: #888888">
                批次编号：{{ g.batchCode || "--" }}
              </div>
            </van-cell-group>
            <van-cell-group>
              <p class="label required FormTit"><span></span>工序</p>
              <van-field-select-picker
                label=""
                :supportClear="true"
                placeholder="请选择"
                v-model="g.taskId"
                :columns="g.taskList"
                :option="{ label: 'processName', value: 'taskId' }"
                @confirm="(o) => taskConfirm(o, i)"
                @prePopShow="showTaskDialog"
              />
              <div class="bottomLine"></div>
            </van-cell-group>
            <van-cell-group>
              <p class="label required FormTit"><span></span>操作人</p>
              <van-field-select-picker
                label=""
                :supportClear="true"
                placeholder="提交人姓名"
                v-model="g.operatorId"
                :columns="g.operatorList"
                :option="{ label: 'text', value: 'value' }"
                @confirm="operatorConfirm"
                @prePopShow="showTaskDialog"
              />
              <div class="bottomLine"></div>
            </van-cell-group>
            <van-cell-group>
              <p class="label FormTit"><span></span>合格数</p>
              <van-field
                placeholder="请输入"
                @input="(e) => inputNum(e, i)"
                v-model="g.qualifiedNum"
                @blur="blurQ(i)"
              >
                <template #button>
                  <span>{{
                    subStrText(g.processWorkUnitText, 3) || "--"
                  }}</span>
                </template>
              </van-field>
              <div class="bottomLine"></div>
            </van-cell-group>
            <van-cell-group>
              <p class="label FormTit"><span></span>不合格数</p>
              <van-field
                placeholder="请输入"
                readonly
                @click="showUp(i)"
                v-model="g.notQualifiedNum"
              >
                <template #button>
                  <span>{{
                    subStrText(g.processWorkUnitText, 3) || "--"
                  }}</span>
                </template>
              </van-field>
              <div class="bottomLine"></div>
            </van-cell-group>
            <van-cell-group>
              <p class="label FormTit"><span></span>不合格原因</p>
              <!-- <van-field disabled v-model="g.notQualifiedReasonText" /> -->
              <div style="color: c8c9cc; padding: 0.1rem 0.16rem">
                {{ g.notQualifiedReasonText || "--" }}
              </div>
            </van-cell-group>
            <van-cell-group>
              <p class="label FormTit"><span></span>备注</p>
              <van-field
                v-model="g.remark"
                rows="2"
                autosize
                label=""
                type="textarea"
                maxlength="500"
                placeholder="请输入备注"
                show-word-limit
              />
            </van-cell-group>
          </div>
          <div class="examinewrap" v-show="!fakeData">
            <van-tabs
              v-model="activeTab"
              color="#1890ff"
              v-if="productionType && qualityType"
            >
              <van-tab title="生产审批"></van-tab>
              <van-tab title="质检审批"></van-tab>
            </van-tabs>
            <Examine
              style="margin-top: 0.12rem;margin-bottom:0.42rem"
              @submitProcess="productProcess"
              @fieldError="productDtos = null"
              @getUserState="getUserState"
              type="0"
              :key="examKey"
              id="MESS_TASK_REPORT_WORK_APPLY_FOR_PRODUCT"
              ref="examineP"
              v-show="activeTab == 0"
              v-if="productionType"
              @loadNodeDtos="loadNodeDtosP"
            />
            <Examine
              style="margin-top: 0.12rem;margin-bottom:0.42rem"
              @submitProcess="qualityProcess"
              @fieldError="qualityDtos = null"
              @getUserState="getUserState"
              type="0"
              :key="2"
              id="MESS_TASK_REPORT_WORK_APPLY_FOR_QUALITY"
              ref="examineQ"
              v-show="activeTab == 1"
              v-if="qualityType"
              @loadNodeDtos="loadNodeDtosQ"
            />
          </div>
        </div>
      </div>
      <div class="search-bottoms">
        <span class="btncancel" @click="btncancel">取消</span>
        <van-button
          type="info"
          :loading="loadingSubmit"
          class="btnconfirm"
          loading-text="提交中..."
          @click="submitProcess"
          >提交</van-button
        >
      </div>
      <div
        class="pda-btn"
        @click="focusPDA"
        ref="floatButton"
        :style="{ left: `${left}px`, top: top + 'px' }"
      >
        <img src="@/assets/img/pdaScan.png" alt="" />
      </div>
    </div>
    <not-qualified-num
      ref="NotQualifiedNum"
      :dataSource="dictOptions"
      @comfirm="comfirmReason"
    ></not-qualified-num>
  </div>
</template>
<script>
import * as dd from "dingtalk-jsapi";
import Navbar from "@/components/navBar/navBar_right";
import Examine from "@/components/examine";
import { ajaxGetDictItems } from "@/api/api";
import { commafy, clearNoNum, accAdd, accSub, setTitle } from "@/utils/util";
import VanFieldCheckbox from "@/components/ActionSheet/VanFieldCheckbox";
import BatchProduction from "@/components/BatchProduction";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import NotQualifiedNum from "@/components/choiceuse/NotQualifiedNum";
import { Dialog } from "vant";
import {
  queryBatchTaskReportList,
  messProductBatchPageList,
  taskDetailApi,
  getReportTeamUserListByTaskId,
  reportBatchAdd,
} from "@/api/mobile";
export default {
  name: "materialRequisitionForm", //领料单
  components: {
    Navbar,
    VanFieldCheckbox,
    BatchProduction,
    qrcode: () => import("@/components/scanCode"),
    VanFieldSelectPicker,
    NotQualifiedNum,
    Examine,
  },

  data() {
    return {
      appTitle: "批次报工",
      appTitleText: "批次报工",
      commafy,
      activeTab: 0,
      loadingSubmit: false,
      examKey: 1,
      optionsFPor: [], //操作人下拉数据
      failedOperatorIdText: "", //操作人
      handleList: [],
      num: "",
      batchInfo: {}, // 扫码结果
      batchCode: "", // 顶部搜索
      formData: {
        qrcode: false,
      },
      torchActive: true,
      camera: "off",
      focused: false,
      batchCodeList: [],
      currentLoginUser: "",
      currentIndex: null,
      dictOptions: [],
      defaultNQTable: [],
      showPeopleSlect: false,
      fakeData: false,
      productDtos: null,
      qualityDtos: null,
      qualityType: false,
      productionType: false,

      clientWidth: 0,
      clientHeight: 0,
      timer: null,
      currentTop: 0,
      left: -50,
      top: 420,
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showPeopleSlect) {
      this.$refs.examine.closePicker();
      next(false);
    }
    if (this.$refs.NotQualifiedNum.show) {
      this.$refs.NotQualifiedNum.show = false;
      this.upDateTitle("批次报工");
      next(false);
    } else {
      next();
    }
  },
  computed: {},
  watch: {
    handleList(newVal) {
      let qualityType = false;
      let productionType = false;
      if (newVal && newVal.length > 0) {
        newVal.forEach((item) => {
          if (item.type == "production") {
            productionType = true;
          } else if (item.type == "quality") {
            qualityType = true;
          }
        });
      }
      if (productionType && !qualityType) {
        this.activeTab = 0;
      }
      if (!productionType && qualityType) {
        this.activeTab = 1;
      }
      this.qualityType = qualityType;
      this.productionType = productionType;
    },
  },
  mounted() {
    this.left = document.documentElement.clientWidth - 56;
    this.top = document.documentElement.clientHeight - 100;
    // this.$refs.PDAScan.focus()
    this.$nextTick(() => {
      const floatButton = this.$refs.floatButton;
      floatButton.addEventListener("touchstart", () => {
        floatButton.style.transition = "none";
      });

      // 在拖拽的过程中，组件应该跟随手指的移动而移动。
      floatButton.addEventListener("touchmove", (e) => {
        console.log("移动中", e);
        if (e.targetTouches.length === 1) {
          // 一根手指
          let touch = e.targetTouches[0];
          this.left = touch.clientX - 22;
          this.top = touch.clientY - 22;
        }
      });

      // 拖拽结束以后，重新调整组件的位置并重新设置过度动画。
      floatButton.addEventListener("touchend", () => {
        floatButton.style.transition = "all 0.3s";
        if (this.left > document.documentElement.clientWidth / 2) {
          this.left = document.documentElement.clientWidth - 56;
        } else {
          this.left = 12;
        }
      });
    });
    this.focusPDA();
    this.focused = true;
  },
  created() {
    ajaxGetDictItems("mess_not_qualified_reason", null).then((res) => {
      if (res.success) {
        this.dictOptions = res.result.map((item) => {
          let obj = {
            notQualifiedReasonText: item.text,
            notQualifiedReason: item.value,
            notQualifiedNum: "",
          };
          this.defaultNQTable.push(obj);
          return obj;
        });
      } else {
        this.$toast(res.message);
      }
    });
    this.getDetail();
  },
  methods: {
    loadNodeDtosP(v) {
      if (v.length === 0) {
        this.productionType = false;
      }
    },
    loadNodeDtosQ(v) {
      if (v.length === 0) {
        this.qualityType = false;
      }
    },
    onBtnClicked() {
      this.$emit("onFloatBtnClicked");
    },
    handleScrollStart() {
      this.timer && clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.handleScrollEnd();
      }, 300);
      this.currentTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (this.left > this.clientWidth / 2) {
        this.left = this.clientWidth - this.itemWidth / 2;
      } else {
        this.left = -this.itemWidth / 2;
      }
    },
    handleScrollEnd() {
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop === this.currentTop) {
        if (this.left > this.clientWidth / 2) {
          this.left = this.clientWidth - this.itemWidth - this.gapWidth;
        } else {
          this.left = this.gapWidth;
        }
        clearTimeout(this.timer);
      }
    },
    blurSearch() {
      setTimeout(() => {
        this.focused = false;
      }, 200);
    },
    inputscan(v) {
      var str = v.target.value;
      var startStr = str.indexOf("{");
      var endStr = str.indexOf("}");
      var jsonStr = str.substring(startStr, str.length);
      if (startStr != -1 && endStr != -1) {
        var objByStr = eval("(" + jsonStr + ")");
        this.addBatchById(objByStr.id);
      }
    },
    focusPDA() {
      this.$refs.PDAScan.focus();
      this.$refs.PDAScan.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.PDAScan.removeAttribute("readonly");
        this.focused = true;
      }, 200);
    },
    onScanning(code) {
      const activeNode = document.activeElement; // 当前聚焦的输入框
      //为当前焦点元素赋值
      if (
        activeNode.nodeName === "INPUT" ||
        activeNode.nodeName === "TEXTAREA"
      ) {
        activeNode.value = "";
      }
      console.log("获取到的条形码:", code); //获取到的条形码
      let codeInfo = JSON.parse(code);
      this.addBatchById(codeInfo.id);
    },
    btncancel() {
      Dialog.confirm({
        title: "是否确认离开此页面",
        // message: '弹窗内容',
      })
        .then(() => {
          this.$router.go(-1);
          // on confirm
        })
        .catch(() => {
          // on cancel
        });
    },
    upDateTitle(v) {
      this.appTitle = v;
      setTitle(this.appTitle);
    },
    getUserState(v) {
      this.showPeopleSlect = v;
    },
    comfirmReason(obj, arr) {
      this.upDateTitle("批次报工");
      let i = this.currentIndex;
      this.handleList[i].notQualifiedReason = obj.notQualifiedReason;
      this.handleList[i].notQualifiedReasonText = obj.notQualifiedReasonText;
      this.handleList[i].notQualifiedNum = obj.notQualifiedNum;
      this.handleList[i].dictOptions = arr;
      this.$forceUpdate();
      this.checkValue(
        "notQualifiedNum",
        obj.notQualifiedNum,
        this.handleList[i],
        i
      );
    },
    showUp(i) {
      this.upDateTitle("不合格数输入");
      this.currentIndex = i;
      this.$refs.NotQualifiedNum.showUp(this.handleList[i].dictOptions);
    },
    subStrText(str, length) {
      let newStr = str;
      if (str) {
        if (str.length > length) {
          newStr = str.substr(0, length);
          newStr += "...";
        }
      } else {
        newStr = "--";
      }
      return newStr;
    },
    checkDtos() {
      let qualityType = false;
      let productionType = false;
      if (this.handleList && this.handleList.length > 0) {
        this.handleList.forEach((item) => {
          if (item.type == "production") {
            productionType = true;
          } else if (item.type == "quality") {
            qualityType = true;
          }
        });
      }
      if (productionType && !qualityType) {
        this.activeTab = 0;
      }
      if (!productionType && qualityType) {
        this.activeTab = 1;
      }
      this.qualityType = qualityType;
      this.productionType = productionType;
    },
    taskConfirm(obj, i) {
      if (!obj) {
        this.handleList[i].operatorId = "";
        this.handleList[i].qualifiedNum = "";
        this.handleList[i].notQualifiedNum = "";
        this.handleList[i].notQualifiedReasonText = "";
        this.handleList[i].notQualifiedReason = "";
        this.handleList[i].type = "";
        this.handleList[i].dictOptions = JSON.parse(
          JSON.stringify(this.defaultNQTable)
        );
        this.checkDtos();
        console.log(obj, i, "obji");
      } else {
        if (obj.taskId == this.handleList[i].taskId) {
          this.checkDtos();
          return;
        }
        taskDetailApi({ id: obj.taskId }).then((res) => {
          if (res.success) {
            let item = res.result;
            let tasks = this.batchCodeList.find((t) => t.id == obj.batchId);
            let task = tasks.batchTaskList.find((j) => j.taskId == obj.taskId);
            // console.log('tasks',tasks);
            this.handleList[i].type = obj.type;
            this.handleList[i].qualifiedNum = task.availableNumForReport;
            this.handleList[i].excessCanReportNum = task.excessCanReportNum;
            this.handleList[i].notQualifiedReasonText = "";
            this.handleList[i].notQualifiedReason = "";
            this.handleList[i].dictOptions = JSON.parse(
              JSON.stringify(this.defaultNQTable)
            );
            this.checkDtos();
            this.$forceUpdate();
          } else {
            this.$toast(res.message);
          }
        });
        getReportTeamUserListByTaskId({ taskId: obj.taskId }).then((res) => {
          if (res.success) {
            this.handleList[i].operatorList = res.result;
            if (
              !this.handleList[i].operatorList.find(
                (op) => op.value == this.currentLoginUser.id
              )
            ) {
              this.handleList[i].operatorList.push({
                text: this.currentLoginUser.realname,
                value: this.currentLoginUser.id,
              });
            }
            for (let item of this.handleList[i].operatorList) {
              if (item.value == this.currentLoginUser.id) {
                this.handleList[i].operatorId = [item.value];
              }
            }
            this.handleList[i].operatorId = this.currentLoginUser.id;
          } else {
            this.$toast(res.message);
          }
        });
      }
      console.log(obj, "obj0.0.0.");
    },
    showTaskDialog(callback) {
      callback("show");
    },
    operatorConfirm(obj) {
      console.log(obj, "operatorConfirm");
    },
    // 打开相机
    clickCode() {
      let that = this;
      let platform = localStorage.getItem("currentEnvironment");
      switch (platform) {
        case "iwork":
          console.log("iwork扫码");
          var opt = {
            success: function (res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function (err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          console.log("browser扫码");
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.formData.qrcode = true;
          that.camera = "rear";
          that.$emit("changeScan", that.formData);
          break;
        case "dingding":
          console.log("dingding扫码");
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function (data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
              console.log(data);
            },
            onFail: function (err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    // 扫码结果回调
    onDecode(result) {
      // result, 扫描结果，可以根据自己的需求来实现相应的功能
      this.batchInfo = JSON.parse(result);
      console.log(this.batchInfo, "this.batchInfo");
      this.addBatchById(this.batchInfo.id);
      this.turnCameraOff();
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.formData.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },
    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
    inputNum(e, i) {
      this.handleList[i].qualifiedNum = clearNoNum(e);
      this.blurQ(i);
    },
    blurQ(i) {
      let item = this.handleList[i];
      if (item.qualifiedNum != item.availableNumForReport) {
        this.handleList[i].qualifiedNumByUser = true;
      }
      this.checkValue("qualifiedNum", item.qualifiedNum, item, i);
    },
    inputNotQNum(e, i) {
      this.handleList[i].notQualifiedNum = clearNoNum(e);
    },
    getDetail() {
      this.currentLoginUser = JSON.parse(
        localStorage.getItem("pro__Login_Userinfo")
      ).value;
      let batch = this.$route.query.code;
      console.log(batch, "batchbatchbatch");
      queryBatchTaskReportList({ batchId: batch.id }).then((res) => {
        // queryBatchTaskReportList().then(res => {
        if (res.success) {
          this.batchCodeList = res.result;
          this.addBatchById(batch.id);
        } else {
          this.$toast(res.message);
        }
      });
    },
    // 搜索编号
    goSearch() {
      messProductBatchPageList({ batchCode: this.batchCode }).then((res) => {
        if (res.result.total == 1) {
          let item = res.result.records[0];
          this.addBatchById(item.id);
        } else {
          this.batchCode = "";
          this.focused = false;
          this.$toast("请输入正确的批次编号");
        }
      });
      this.focused = false;
    },
    addBatchById(id) {
      let batch = this.handleList.find((item) => item.batchId == id);
      if (batch) {
        this.batchCode = "";
        // this.focused = false;
        this.$toast("该批次已存在");
        return;
      }
      queryBatchTaskReportList({ batchId: id }).then((res) => {
        if (res.success && res.result.length > 0) {
          this.batchCodeList = res.result;
          let tasks = this.batchCodeList.find((item) => item.id == id);
          let listItem = {
            orderCode: tasks.orderCode,
            orderId: tasks.orderId,
            goodsSpec: tasks.goodsSpec,
            goodsCode: tasks.goodsCode,
            goodsName: tasks.goodsName,
            batchId: tasks.batchId,
            batchCode: tasks.batchCode,
            taskList: [],
            taskId: "",
            taskName: "",
            reportWorkNum: "",
            notQualifiedReason: "",
            notQualifiedReasonText: "",
            operatorDisabled: false, // 操作人是否禁止修改
            qualifiedNumByUser: false, // 合格数是否人为输入
          };
          let task = tasks.batchTaskList[0];
          listItem.taskList = tasks.batchTaskList;
          listItem.taskId = task.taskId;
          listItem.type = task.type;
          listItem.taskName = task.processName;
          taskDetailApi({ id: task.taskId }).then((res) => {
            if (res.success) {
              let detail = res.result;

              listItem.processWorkUnitText = detail.processWorkUnitText;
              if (task.availableNumForReport <= detail.availableNumForReport) {
                listItem.availableNumForReport =
                  task.availableNumForReport > 0
                    ? task.availableNumForReport
                    : "";
                listItem.excessCanReportNum = task.excessCanReportNum;

                let totalQualified = 0;
                let mixQualified = 0;
                for (let i = 0; i < this.handleList.length; i++) {
                  const hand = this.handleList[i];
                  if (
                    hand.taskId == listItem.taskId &&
                    hand.batchId != listItem.batchId
                  ) {
                    let handNum = accAdd(
                      Number(hand.qualifiedNum ? hand.qualifiedNum : 0),
                      Number(hand.notQualifiedNum ? hand.notQualifiedNum : 0)
                    );
                    totalQualified += handNum;
                  }
                }
                mixQualified = accSub(
                  detail.availableNumForReport,
                  totalQualified
                );
                if (this.handleList.length > 0) {
                  if (mixQualified > task.availableNumForReport) {
                    listItem.qualifiedNum = task.availableNumForReport;
                    console.log(
                      "listItem.qualifiedNum111:",
                      listItem.qualifiedNum
                    );
                  } else {
                    listItem.qualifiedNum =
                      mixQualified > 0 ? mixQualified : "";
                    console.log(
                      "listItem.qualifiedNum222:",
                      listItem.qualifiedNum
                    );
                  }
                } else {
                  listItem.qualifiedNum = task.availableNumForReport;
                  console.log(
                    "listItem.qualifiedNum333:",
                    listItem.qualifiedNum
                  );
                }
              } else if (
                task.availableNumForReport > detail.availableNumForReport
              ) {
                listItem.availableNumForReport = detail.availableNumForReport;
                listItem.excessCanReportNum = detail.excessCanReportNum;
                // listItem.qualifiedNum = detail.availableNumForReport
                let totalQualified = 0;
                let mixQualified = 0;
                for (let i = 0; i < this.handleList.length; i++) {
                  const hand = this.handleList[i];
                  if (
                    hand.taskId == listItem.taskId &&
                    hand.batchId != listItem.batchId
                  ) {
                    let handNum = accAdd(
                      Number(hand.qualifiedNum ? hand.qualifiedNum : 0),
                      Number(hand.notQualifiedNum ? hand.notQualifiedNum : 0)
                    );
                    totalQualified += handNum;
                  }
                }
                mixQualified = accSub(
                  detail.availableNumForReport,
                  totalQualified
                );
                if (this.handleList.length > 0) {
                  if (mixQualified > task.availableNumForReport) {
                    listItem.qualifiedNum = task.availableNumForReport;
                    console.log(
                      "listItem.qualifiedNum444:",
                      listItem.qualifiedNum
                    );
                  } else {
                    listItem.qualifiedNum =
                      mixQualified > 0 ? mixQualified : "";
                    console.log(
                      "listItem.qualifiedNum555:",
                      listItem.qualifiedNum
                    );
                  }
                } else {
                  listItem.qualifiedNum = detail.availableNumForReport;
                  console.log(
                    "listItem.qualifiedNum666:",
                    listItem.qualifiedNum
                  );
                }
              }
              getReportTeamUserListByTaskId({ taskId: task.taskId }).then(
                (res) => {
                  if (res.success) {
                    listItem.operatorList = res.result;
                    if (
                      !listItem.operatorList.find(
                        (op) => op.value == this.currentLoginUser.id
                      )
                    ) {
                      listItem.operatorList.push({
                        text: this.currentLoginUser.realname,
                        value: this.currentLoginUser.id,
                      });
                    }
                    for (let item of listItem.operatorList) {
                      if (item.value == this.currentLoginUser.id) {
                        listItem.operatorId = [item.value];
                      }
                    }
                    listItem.operatorId = this.currentLoginUser.id;
                    listItem.dictOptions = this.dictOptions;
                    this.fakeData = false;
                    this.handleList.push(listItem);
                    this.$nextTick(() => {
                      let self = document.querySelector(".list-box");
                      let examinewrap = document.querySelector(".examinewrap");
                      let itemHeight = document.querySelector(".item-height");
                      console.log(
                        itemHeight.clientHeight,
                        "examinewrap:",
                        self.scrollHeight,
                        "-",
                        examinewrap.clientHeight
                      );
                      self.scrollTop =
                        self.scrollHeight - examinewrap.clientHeight - itemHeight.clientHeight;
                    });
                  } else {
                    this.$toast(res.message);
                  }
                }
              );
              this.batchCode = "";
              // this.focused = false;
            } else {
              this.batchCode = "";
              // this.focused = false;
              this.$toast(res.message);
            }
          });
        } else {
          this.batchCode = "";
          // this.focused = false;
          this.$toast("当前批次无可报工信息");
        }
      });
    },
    checkTaskTotalNum(item, handIndex) {
      let total = 0;
      let itemNum = accAdd(
        Number(item.qualifiedNum ? item.qualifiedNum : 0),
        Number(item.notQualifiedNum ? item.notQualifiedNum : 0)
      );
      total += itemNum;
      for (let i = 0; i < this.handleList.length; i++) {
        const hand = this.handleList[i];
        if (hand.taskId == item.taskId && hand.batchId != item.batchId) {
          let handNum = accAdd(
            Number(hand.qualifiedNum ? hand.qualifiedNum : 0),
            Number(hand.notQualifiedNum ? hand.notQualifiedNum : 0)
          );
          total += handNum;
          taskDetailApi({ id: item.taskId }).then((res) => {
            if (res.success) {
              let detail = res.result;
              console.log(
                total,
                detail,
                "this.handleList[handIndex]this.handleList[handIndex]"
              );
              if (total > detail.availableNumForReport) {
                this.handleList[handIndex].qualifiedNum = "";
                this.handleList[handIndex].dictOptions = JSON.parse(
                  JSON.stringify(this.defaultNQTable)
                );
                this.handleList[handIndex].notQualifiedNum = "";
                this.handleList[handIndex].notQualifiedReasonText = "";
                this.handleList[handIndex].notQualifiedReason = "";
                this.handleList[handIndex].reportWorkNum = "";
                this.$toast(
                  `同一工序报工总数不能大于最大应生产数，请修改工序${this.handleList[handIndex].taskName}下的合格品、和不合格品的报工数！`
                );
                return false;
              } else {
                return true;
              }
            }
          });
        }
      }
    },
    checkValue(type, value, item, handIndex) {
      if (type == "qualifiedNum") {
        let num = accSub(
          Number(item.excessCanReportNum),
          Number(item.notQualifiedNum ? item.notQualifiedNum : 0)
        );
        if (Number(value) > Number(num)) {
          item[type] = "0";
          item.reportWorkNum = item.notQualifiedNum;
          this.checkTaskTotalNum(item, handIndex);
          this.$toast("报工总数不能大于最大应生产数！");
          return;
        } else {
          if (item.notQualifiedNum) {
            item.reportWorkNum = accAdd(
              Number(item.notQualifiedNum),
              Number(item.qualifiedNum)
            );
            this.checkTaskTotalNum(item, handIndex);
          } else {
            item.reportWorkNum = item.qualifiedNum;
            this.checkTaskTotalNum(item, handIndex);
          }
        }
      } else {
        let num = accSub(
          Number(item.excessCanReportNum),
          Number(item.qualifiedNum ? item.qualifiedNum : 0)
        );
        let qnum = accSub(Number(item.excessCanReportNum), Number(value));
        if (Number(value) > Number(num)) {
          if (!item.qualifiedNumByUser) {
            item.qualifiedNum = Number(qnum) > 0 ? qnum : 0;
          }
          item.reportWorkNum = accAdd(Number(value), Number(item.qualifiedNum));
          this.checkTaskTotalNum(item, handIndex);
          let report = accAdd(Number(value), Number(item.qualifiedNum));
          console.log(
            item.qualifiedNumByUser,
            "item.qualifiedNumByUser",
            item.excessCanReportNum
          );
          if (item.qualifiedNumByUser) {
            item.reportWorkNum = report > item.excessCanReportNum ? "" : report;
            this.checkTaskTotalNum(item, handIndex);
            if (report > item.excessCanReportNum) {
              item.dictOptions = JSON.parse(
                JSON.stringify(this.defaultNQTable)
              );
              item.notQualifiedNum = "";
              item.notQualifiedReasonText = "";
              item.notQualifiedReason = "";
              this.$toast("报工总数不能大于最大应生产数！");
              return;
            }
          } else {
            if (report > item.excessCanReportNum) {
              item.dictOptions = JSON.parse(
                JSON.stringify(this.defaultNQTable)
              );
              item.notQualifiedNum = "";
              item.notQualifiedReasonText = "";
              item.notQualifiedReason = "";
              item.reportWorkNum = "";
              this.$toast("报工总数不能大于最大应生产数！");
              return;
            }
            item.reportWorkNum = report;
            this.checkTaskTotalNum(item, handIndex);
          }
        } else {
          if (item.qualifiedNum) {
            item.reportWorkNum = accAdd(
              Number(item.notQualifiedNum),
              Number(item.qualifiedNum)
            );
            this.checkTaskTotalNum(item, handIndex);
          } else {
            item.reportWorkNum = item.notQualifiedNum;
            this.checkTaskTotalNum(item, handIndex);
          }
        }
      }
    },
    // 删除一条
    clearItem(i) {
      if (i === 0 && this.handleList.length === 1) {
        this.fakeData = true;
      }
      this.handleList.splice(i, 1);
    },
    productProcess(e) {
      if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.productDtos = e;
        // this.btnConfirm(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examineP.confirm();
      }
    },
    qualityProcess(e) {
      if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.qualityDtos = e;
        // this.btnConfirm(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examineQ.confirm();
      }
    },
    submitProcess() {
      if (this.productionType) {
        this.$refs.examineP.confirm();
      }
      if (this.qualityType) {
        this.$refs.examineQ.confirm();
      }
      this.$nextTick(() => {
        if (this.productionType && !this.productDtos) {
          this.$toast("节点信息必填");
          return;
        }
        if (this.qualityType && !this.qualityDtos) {
          this.$toast("节点信息必填");
          return;
        }
        console.log("提交吧");
        this.btnConfirm();
      });
    },
    // 表单提交
    btnConfirm(processDataVo) {
      console.log(this.handleList);
      this.loadingSubmit = true;
      let dtoList = [];
      let productionList = [];
      let qualityList = [];
      if (this.handleList.length == 0) {
        this.$toast(`请添加批次`);
        this.loadingSubmit = false;
        return;
      }
      for (let i = 0; i < this.handleList.length; i++) {
        const item = this.handleList[i];
        if (!item.operatorId) {
          this.$toast(`报工批次(${i + 1})请选择操作人`);
          this.loadingSubmit = false;
          return;
        }
        if (!item.taskId) {
          this.$toast(`报工批次(${i + 1})请选择工序`);
          this.loadingSubmit = false;
          return;
        }
        if (!Number(item.notQualifiedNum) && !Number(item.qualifiedNum)) {
          this.$toast(`报工批次(${i + 1})请输入合格数或不合格数`);
          this.loadingSubmit = false;
          return;
        }
        let obj = {
          notQualifiedNum: item.notQualifiedNum ? item.notQualifiedNum : "",
          notQualifiedReason: item.notQualifiedReason,
          operatorId: item.operatorId,
          orderId: item.orderId,
          qualifiedNum: item.qualifiedNum ? item.qualifiedNum : "",
          reportWorkNum: item.reportWorkNum ? item.reportWorkNum : "",
          taskId: item.taskId,
          batchId: item.batchId,
          batchCode: item.batchCode,
          type: item.type,
          remark: item.remark,
        };
        if (item.type == "production") {
          productionList.push(obj);
        }
        if (item.type == "quality") {
          qualityList.push(obj);
        }
        // dtoList.push(obj);
        // console.log(dtoList);
      }
      // let parameter = {
      //   dtoList: dtoList,
      //   processDataVo: processDataVo,
      //   reportType: "production",
      // };
      if (this.productionType) {
        reportBatchAdd({
          dtoList: productionList,
          processDataVo: this.productDtos,
          reportType: "production",
        }).then((res) => {
          this.loadingSubmit = false;
          if (res.code == 200) {
            this.$toast(res.message);
            this.$router.go(-1);
          } else {
            this.$toast(res.message);
          }
        });
      }
      if (this.qualityType) {
        reportBatchAdd({
          dtoList: qualityList,
          processDataVo: this.qualityDtos,
          reportType: "quality",
        }).then((res) => {
          this.loadingSubmit = false;
          if (res.code == 200) {
            this.$toast(res.message);
            this.$router.go(-1);
          } else {
            this.$toast(res.message);
          }
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.sel {
  background: #fff;
  padding: 0px 15px;
  border: solid 1px #f0f0f0;
  border-radius: 15px;
  display: flex;
  align-items: center;
  background: #eee;
  flex: 1;
  input {
    background: #eee;
    border: none;
    height: 37px;
    line-height: 37px;
    width: 100%;
  }
}
.form-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .list-box {
    flex: 1;
    overflow-y: scroll;
  }
}
.top-info {
  padding: 0 0.16rem;
  color: #191f25;
  font-size: 0.15rem;
}
.ordercode {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 0.1rem;
}
.pda-btn {
  width: 0.5rem;
  height: 0.5rem;
  position: fixed;
  bottom: 1rem;
  right: 0.1rem;
  border-radius: 50%;
  background: #f6f6f6;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0rem 0.05rem 0.05rem rgba(0, 0, 0, 0.4);
  box-sizing: border-box;
  border: solid 0.01rem rgba(24, 143, 255, 0.7);
  img {
    width: 0.25rem;
    height: 0.25rem;
  }
}
.search-bottoms {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 9;
  .btncancel {
    flex: 1;
    background: #f6f6f6;
    // border: 0.01rem solid rgba(25, 31, 37, 0.12);
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    margin-right: 0.11rem;
    color: #191f25;
  }
  .btnconfirm {
    flex: 1.5;
    background: #1890ff;
    box-sizing: border-box;
    font-size: 0.16rem;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    color: #ffffff;
  }
}
</style>
